package com.apes.scm.account.method;

/**
 * 功能：批次算法
 *
 * @author xul
 * @create 2018-03-14 16:44
 */
public abstract class BatchMethod<S extends Batch> implements Method<S> {

    @Override
    public void execute(final double total) {
        if (total <= 0) {
            throw new RuntimeException("请输入大于零的数据！");
        }
        Iterable<S> batches = wrap();
        if (batches == null) throw new RuntimeException("输入批次数据不允许为空！");
        boolean succeed = false;
        double handle = 0;  /*已处理量*/
        for (S batch : batches) {
            double increment; /*增量*/
            if (handle + batch.getQty() >= total) {
                increment = total - handle;
                succeed = true;
            } else {
                increment = batch.getQty();
            }
            handle += increment;
            succeed(batch, increment);
            batch.changeQty(-1 * increment);
            if (succeed) break;
        }

        double surplus = total - handle; /*剩余量*/

        /*量不足*/
        if ((!succeed) || (surplus != 0)) {
            error(surplus);
        }
    }

    /**
     * 功能：数据包装
     */
    public abstract Iterable<S> wrap();

    /**
     * 功能：批次处理
     */
    public abstract void succeed(S batch, final double increment);

    /**
     * 功能：量不足后异常处理
     */
    public abstract void error(final double surplus);

}
